import datetime

from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.versioning import QueryParameterVersioning, URLPathVersioning, AcceptHeaderVersioning
from rest_framework.parsers import JSONParser, FormParser
from rest_framework.negotiation import DefaultContentNegotiation
from rest_framework import serializers
from django.core.validators import EmailValidator, RegexValidator
from rest_framework import exceptions

from api import models


class HomeView(APIView):
    versioning_class = URLPathVersioning
    # 所有的解析器
    parser_classes = [JSONParser, FormParser]
    # 根据请求，匹配解析器
    content_negotiation_class = DefaultContentNegotiation

    def get(self, request, *args, **kwargs):
        print(request.version)
        # url = request.versioning_scheme.reverse("hh",request=request)
        # # 反向生成
        # print(url)
        self.dispatch
        return Response({'message': 'Welcome to the API'})

    def post(self, request, *args, **kwargs):
        print(request.data, type(request.data))
        return Response("OK")


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ["name", "age", "depart", "tags"]


class UserView(APIView):
    def get(self, *args, **kwargs):
        # 获取数据
        # 序列化
        query_set = models.UserInfo.objects.all()
        ser = UserSerializer(instance=query_set, many=True)
        context = {
            "status": True,
            "data": ser.data
        }
        return Response(context)


class DepartSerializer(serializers.Serializer):
    title = serializers.CharField(required=True, max_length=20, min_length=6)
    order = serializers.IntegerField(required=True, max_value=100, min_value=10)
    level = serializers.ChoiceField(choices=[("1", "高级"), (2, "中级")])
    email = serializers.CharField(validators=[RegexValidator(r"\d+", message="邮箱格式错误"), ])

    def validate_email(self, value):
        print(value)
        if len(value) > 6:
            raise exceptions.ValidationError("字段钩子校验失败")
        return value

    def validate(self, attrs):
        print("validate", attrs)

        return attrs


class DepartModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Depart
        fields = ["title", "order", "count"]
        extra_kwargs = {
            "title": {"max_length": 5, "min_length": "1"},
            "order": {"min_value": 5},
            "count": {"validators": [RegexValidator(r"\d+", message="必须是数字 ")]}
        }


class DepartView(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)

        # 校验
        ser = DepartSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        print(ser.validated_data)
        return Response("OK")


class UsModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ["name", "age", "gender", "depart", "tags"]

    def validate_depart(self, value):
        if value.id > 1:
            return value
        raise exceptions.ValidationError("部门id错误")

    def validate_tags(self, value):
        print(value)
        return value


class UsView(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)

        # 校验
        ser = UsModelSerializer(data=request.data)
        if ser.is_valid():
            print("视图", ser.validated_data)
            ser.save()
        else:
            print("视图", ser.errors)

        return Response("OK")


class DpModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Depart
        fields = "__all__"
        extra_kwargs = {
            "id": {"read_only": True},
            "count": {"write_only": True}
        }


class DpView(APIView):
    def post(self, request, *args, **kwargs):
        ser = DpModelSerializer(data=request.data)
        if ser.is_valid():
            instance = ser.save()
            print(instance)
            xx = DpModelSerializer(instance=instance)
            return Response(xx.data)

        else:
            return Response(ser.errors)


class P1ModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Depart
        fields = "__all__"


class UusModelSerializer(serializers.ModelSerializer):
    v1 = P1ModelSerializer(read_only=True, source="depart")

    # gender_info = serializers.CharField(source="get_gender_display",read_only=True)
    class Meta:
        model = models.UserInfo
        fields = ["id", "name", "age", "gender", "depart", "v1"]
        extra_kwargs = {
            "id": {"read_only": True},
            # 序列化的时候不会展示
            "gender": {"write_only": True}
        }

    # def get_v1(self,obj):
    #     return {'id':obj.gender,"text":obj.get_gender_display()}


class UusView(APIView):
    def post(self, request, *args, **kwargs):
        ser = UusModelSerializer(data=request.data)
        if ser.is_valid():
            return Response(ser.data)

        else:
            return Response(ser.errors)


class NbCharField(serializers.IntegerField):
    def __init__(self,method_name=None,**kwargs):
        self.method_name = method_name

        super().__init__(**kwargs)

    def bind(self,field_name,parent):
        if self.method_name is None:
            self.method_name = f'xget_{field_name}'

        super().bind(field_name,parent)

    def get_attribute(self, instance):
        method = getattr(self.parent,self.method_name)
        return method(instance)
class NbModelSerializer(serializers.ModelSerializer):
    gender = serializers.CharField()

    class Meta:
        model = models.NbUserInfo
        fields = ["id", "name", "age", "gender"]
        extra_kwargs = {
            "id": {"read_only": True}
        }

    def get_gender(self, obj):
        return obj.get_gender_display()


class NbView(APIView):
    def post(self, request, *args, **kwargs):
        ser = NbModelSerializer(data=request.data)
        if ser.is_valid():
            instance = ser.save()
            return Response(ser.data)

        else:
            return Response(ser.errors)
